<template>
	<view class="page">
		<view>{{title}}</view>
	</view>
</template>

<script>
	import {
		bindTrainee
	} from '@/utils/api.js'
	import {
		baseUrl
	} from '@/utils/config.js'
	export default {
		data() {
			return {
				title: '绑定中'
			};
		},
		async onLoad(e) {
			const query = this.getQuery()
			if (query.code) {
				try {
					const {
						appId,
						id
					} = this.parseQueryString(query.state)
					await bindTrainee({
						appId,
						traineeId: id,
						code: query.code
					})
					this.title = '绑定成功'
				} catch (e) {
					this.title = '绑定失败'
				}
			} else {
				const urlPath = `${baseUrl}/#/pages/autoBindStudent/autoBindStudent`
				const url =
					`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${e.appId}&redirect_uri=${encodeURIComponent(urlPath)}&response_type=code&scope=snsapi_userinfo&state=${this.objectToQueryString(e)}`
				console.log(url)
				window.location = url
			}

		},
		methods: {
			getQuery() {
				const stringArr = window.location.search.slice(1).split('&')
				const query = {}
				for (let v of stringArr) {
					const arr = v.split('=')
					query[arr[0]] = arr[1]
				}
				return query
			},
			objectToQueryString(obj) {
				return Object.keys(obj)
					.map(key => `${encodeURIComponent(key)}=${encodeURIComponent(obj[key])}`)
					.join(',');
			},
			parseQueryString(queryString) {
				const obj = {};
				const pairs = decodeURIComponent(queryString).split(',');
				pairs.forEach(pair => {
					const [key, value] = pair.split('=');
					obj[key] = isNaN(value) ? value : Number(value);
				});

				return obj;
			},
		}
	}
</script>

<style lang="scss">
	.page {
		min-height: 100vh;
		display: flex;
		align-items: center;
		justify-content: center;
	}
</style>